import { message, Row, Col, Image, Modal } from "antd";
import axios from "axios";
import React, { useEffect, useRef, useState } from "react";
import add from "../../assets/images/add1.webp";

interface ListItemType {
  url: string;
  name: string;
}

const Index = () => {
  const input = useRef<HTMLInputElement | null>(null);
  const [list, setList] = useState<ListItemType[]>([]);

  const onClick = () => {
    if (input.current) {
      input.current.click();
    }
  };

  const onChange = async () => {
    if (input.current && input.current.files) {
      // 获取文件
      const file = input.current.files[0];

      if (!file.type.includes("image")) {
        message.error("上传的只可以是图片~");
        return;
      }

      if (file.size > 2 * 1024 ** 2) {
        message.error("上传的图片大小不可以超过2MB");
        return;
      }

      const formData = new FormData();
      formData.append("chunk", file, file.name);

      const resp = await axios.post("/api/upload/oss", formData);
      console.log(resp.data);
      fetchList();
    }
  };

  const fetchList = async () => {
    const resp = await axios.get("/api/upload/oss/list");
    setList(resp.data.data.objects);
  };

  const deleteImage = async (v: ListItemType) => {
    Modal.confirm({
      title: "确认要删除吗？",
      async onOk() {
        const resp = await axios.delete("/api/upload/oss/delete", {
          data: { name: v.name },
        });
        fetchList();
      },
    });
  };

  useEffect(() => {
    fetchList();
  }, []);

  return (
    <div>
      <div style={{ textAlign: "center" }}>
        <input
          ref={input}
          type="file"
          style={{ display: "none" }}
          onChange={() => onChange()}
        />
        <img
          src={add}
          alt=""
          style={{
            width: 200,
            height: 200,
            border: "1px solid #ccc",
            padding: 10,
          }}
          onClick={() => onClick()}
        />
      </div>
      <Row>
        {list.map((v, i) => {
          return (
            <Col span={6} key={i}>
              <div>
                <h3 style={{ textAlign: "right" }}>
                  <span onClick={() => deleteImage(v)}>X</span>
                </h3>
                <Image
                  src={v.url}
                  alt=""
                  style={{
                    width: "100%",
                    height: 200,
                    padding: 10,
                    objectFit: "cover",
                  }}
                />
              </div>
            </Col>
          );
        })}
      </Row>
    </div>
  );
};

export default Index;
